package yesjava.news.web;

import yesjava.news.entity.News;
import yesjava.news.entity.User;
import yesjava.news.service.NewsService;
import yesjava.news.service.NewsServiceImpl;
import yesjava.news.service.UserService;
import yesjava.news.service.UserServiceImpl;
import yesjava.news.utils.EmailUtil;
import yesjava.news.utils.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/submit_update.do")
public class SubmitUpdateNewsServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();
    private UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String readCountTxt = request.getParameter("readCount");
        Integer readCount = (readCountTxt==null)?0:(Integer.parseInt(readCountTxt.trim())) ;
        String checkedTxt = request.getParameter("checked");
        Integer checked = (checkedTxt==null)?0:(Integer.parseInt(checkedTxt.trim())) ;

        String showTxt = request.getParameter("show");
        Integer show = (showTxt==null)?0:(Integer.parseInt(showTxt.trim())) ;

        News news = newsService.getNewsById(id);

        news.setTitle(title).setContent(content).setReadCount(readCount).setShow(show).setChecked(checked);

        newsService.updateById(news);
//        是否发送邮件
        String sendMailTxt = request.getParameter("sendMail");
        Integer sendMail = (sendMailTxt==null)?0:(Integer.parseInt(sendMailTxt.trim())) ;
        if(sendMail==1){
            Integer creatorUserId = news.getCreatorBy();
            User creator = userService.getUserById(creatorUserId);
            String mailAddress = creator.getEmail();
            if(mailAddress!=null && mailAddress.indexOf("@")!=-1){
                String mailTitle= "XX系统通知-新闻审核"+(news.getChecked()==1?"通过":"不通过");
                String mailContent= "您输入的新闻【" +news.getTitle()+"】在 " + LocalDate.now()+ "审核"+(news.getChecked()==1?"通过":"不通过")+"，如有异议请联系110";
                EmailUtil.sendEmail(List.of(mailAddress),mailTitle,mailContent,true);
            }else {
                throw new RuntimeException("Email 邮箱不存在或 Email邮箱有误！");
            }
        }

        Map<String,Object> map  = new HashMap<>();
        map.put("success",true);
        JSONUtil.printJSON(map,response);



    }
}
